<!DOCTYPE html>
<html lang="en-US">
  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width,initial-scale=1">
    <title>Proxy 对象 | 20秒的勇气</title>
    <meta name="generator" content="VuePress 1.5.3">
    <script>var _hmt = _hmt || [];
      (function() {
        var hm = document.createElement("script");
        hm.src = "https://hm.baidu.com/hm.js?01611e9c2d4c65531fe791d0a83e6ebd";
        var s = document.getElementsByTagName("script")[0]; 
        s.parentNode.insertBefore(hm, s);
      })()</script>
    <meta name="description" content="欢迎来到wenbintian的博客">
    <link rel="preload" href="/blog/assets/css/0.styles.5dc057b1.css" as="style"><link rel="preload" href="/blog/assets/js/app.2a047d56.js" as="script"><link rel="preload" href="/blog/assets/js/2.cc145974.js" as="script"><link rel="preload" href="/blog/assets/js/20.713720d3.js" as="script"><link rel="prefetch" href="/blog/assets/js/10.dc9f6a74.js"><link rel="prefetch" href="/blog/assets/js/11.f7ecaf96.js"><link rel="prefetch" href="/blog/assets/js/12.4363725a.js"><link rel="prefetch" href="/blog/assets/js/13.0fd4b251.js"><link rel="prefetch" href="/blog/assets/js/14.edc7bd5f.js"><link rel="prefetch" href="/blog/assets/js/15.647c0964.js"><link rel="prefetch" href="/blog/assets/js/16.2e8857c5.js"><link rel="prefetch" href="/blog/assets/js/17.1c7cc9ee.js"><link rel="prefetch" href="/blog/assets/js/18.bf88a22d.js"><link rel="prefetch" href="/blog/assets/js/19.1433c5a8.js"><link rel="prefetch" href="/blog/assets/js/21.51a3d47b.js"><link rel="prefetch" href="/blog/assets/js/22.04488762.js"><link rel="prefetch" href="/blog/assets/js/23.b9337410.js"><link rel="prefetch" href="/blog/assets/js/24.d0d5b562.js"><link rel="prefetch" href="/blog/assets/js/25.e76a54ef.js"><link rel="prefetch" href="/blog/assets/js/26.006d0afa.js"><link rel="prefetch" href="/blog/assets/js/27.38ec3468.js"><link rel="prefetch" href="/blog/assets/js/28.c8cf7077.js"><link rel="prefetch" href="/blog/assets/js/29.70f03487.js"><link rel="prefetch" href="/blog/assets/js/3.9bfe5560.js"><link rel="prefetch" href="/blog/assets/js/30.3e6d6ba9.js"><link rel="prefetch" href="/blog/assets/js/31.1dbd85cb.js"><link rel="prefetch" href="/blog/assets/js/32.208e4272.js"><link rel="prefetch" href="/blog/assets/js/33.979228dd.js"><link rel="prefetch" href="/blog/assets/js/34.6ad6fae2.js"><link rel="prefetch" href="/blog/assets/js/35.59b3e591.js"><link rel="prefetch" href="/blog/assets/js/36.7239d917.js"><link rel="prefetch" href="/blog/assets/js/37.a8305f70.js"><link rel="prefetch" href="/blog/assets/js/38.7e3197cd.js"><link rel="prefetch" href="/blog/assets/js/39.1bb3ad3b.js"><link rel="prefetch" href="/blog/assets/js/4.3b6a7e49.js"><link rel="prefetch" href="/blog/assets/js/40.bc263e99.js"><link rel="prefetch" href="/blog/assets/js/41.4ee25f6a.js"><link rel="prefetch" href="/blog/assets/js/42.37c6cc26.js"><link rel="prefetch" href="/blog/assets/js/43.9a40d780.js"><link rel="prefetch" href="/blog/assets/js/44.2eda0bb6.js"><link rel="prefetch" href="/blog/assets/js/45.ce3372d9.js"><link rel="prefetch" href="/blog/assets/js/46.17e44796.js"><link rel="prefetch" href="/blog/assets/js/47.f845ed6d.js"><link rel="prefetch" href="/blog/assets/js/5.bc6e1aa4.js"><link rel="prefetch" href="/blog/assets/js/6.e0f80af7.js"><link rel="prefetch" href="/blog/assets/js/7.c808e2d2.js"><link rel="prefetch" href="/blog/assets/js/8.902b76dc.js"><link rel="prefetch" href="/blog/assets/js/9.9bb8a7fe.js">
    <link rel="stylesheet" href="/blog/assets/css/0.styles.5dc057b1.css">
  </head>
  <body>
    <div id="app" data-server-rendered="true"><div class="theme-container"><header class="navbar"><div class="sidebar-button"><svg xmlns="http://www.w3.org/2000/svg" aria-hidden="true" role="img" viewBox="0 0 448 512" class="icon"><path fill="currentColor" d="M436 124H12c-6.627 0-12-5.373-12-12V80c0-6.627 5.373-12 12-12h424c6.627 0 12 5.373 12 12v32c0 6.627-5.373 12-12 12zm0 160H12c-6.627 0-12-5.373-12-12v-32c0-6.627 5.373-12 12-12h424c6.627 0 12 5.373 12 12v32c0 6.627-5.373 12-12 12zm0 160H12c-6.627 0-12-5.373-12-12v-32c0-6.627 5.373-12 12-12h424c6.627 0 12 5.373 12 12v32c0 6.627-5.373 12-12 12z"></path></svg></div> <a href="/blog/" class="home-link router-link-active"><!----> <span class="site-name">20秒的勇气</span></a> <div class="links"><div class="search-box"><input aria-label="Search" autocomplete="off" spellcheck="false" value=""> <!----></div> <nav class="nav-links can-hide"><div class="nav-item"><a href="/blog/knowledge/" class="nav-link router-link-active">
  知识篇
</a></div><div class="nav-item"><a href="/blog/notes/" class="nav-link">
  随身笔记
</a></div> <a href="https://github.com/wenbintian" target="_blank" rel="noopener noreferrer" class="repo-link">
    GitHub
    <svg xmlns="http://www.w3.org/2000/svg" aria-hidden="true" x="0px" y="0px" viewBox="0 0 100 100" width="15" height="15" class="icon outbound"><path fill="currentColor" d="M18.8,85.1h56l0,0c2.2,0,4-1.8,4-4v-32h-8v28h-48v-48h28v-8h-32l0,0c-2.2,0-4,1.8-4,4v56C14.8,83.3,16.6,85.1,18.8,85.1z"></path> <polygon fill="currentColor" points="45.7,48.7 51.3,54.3 77.2,28.5 77.2,37.2 85.2,37.2 85.2,14.9 62.8,14.9 62.8,22.9 71.5,22.9"></polygon></svg></a></nav></div></header> <div class="sidebar-mask"></div> <aside class="sidebar"><nav class="nav-links"><div class="nav-item"><a href="/blog/knowledge/" class="nav-link router-link-active">
  知识篇
</a></div><div class="nav-item"><a href="/blog/notes/" class="nav-link">
  随身笔记
</a></div> <a href="https://github.com/wenbintian" target="_blank" rel="noopener noreferrer" class="repo-link">
    GitHub
    <svg xmlns="http://www.w3.org/2000/svg" aria-hidden="true" x="0px" y="0px" viewBox="0 0 100 100" width="15" height="15" class="icon outbound"><path fill="currentColor" d="M18.8,85.1h56l0,0c2.2,0,4-1.8,4-4v-32h-8v28h-48v-48h28v-8h-32l0,0c-2.2,0-4,1.8-4,4v56C14.8,83.3,16.6,85.1,18.8,85.1z"></path> <polygon fill="currentColor" points="45.7,48.7 51.3,54.3 77.2,28.5 77.2,37.2 85.2,37.2 85.2,14.9 62.8,14.9 62.8,22.9 71.5,22.9"></polygon></svg></a></nav>  <ul class="sidebar-links"><li><section class="sidebar-group collapsable depth-0"><a href="/blog/knowledge/book/" class="sidebar-heading clickable"><span>读书篇</span> <span class="arrow right"></span></a> <!----></section></li><li><section class="sidebar-group collapsable depth-0"><a href="/blog/knowledge/tool/" class="sidebar-heading clickable"><span>工具篇</span> <span class="arrow right"></span></a> <!----></section></li><li><section class="sidebar-group collapsable depth-0"><a href="/blog/knowledge/css/" class="sidebar-heading clickable"><span>CSS篇</span> <span class="arrow right"></span></a> <!----></section></li><li><section class="sidebar-group collapsable depth-0"><a href="/blog/knowledge/js/" class="sidebar-heading clickable router-link-active open"><span>JS篇</span> <span class="arrow down"></span></a> <ul class="sidebar-links sidebar-group-items"><li><section class="sidebar-group collapsable is-sub-group depth-1"><a href="/blog/knowledge/js/es6/" class="sidebar-heading clickable router-link-active open"><span>ES6</span> <span class="arrow down"></span></a> <ul class="sidebar-links sidebar-group-items"><li><a href="/blog/knowledge/js/es6/promise.html" class="sidebar-link">Promise 对象</a></li><li><a href="/blog/knowledge/js/es6/generator.html" class="sidebar-link">Generator 函数</a></li><li><a href="/blog/knowledge/js/es6/proxy.html" aria-current="page" class="active sidebar-link">Proxy 对象</a><ul class="sidebar-sub-headers"><li class="sidebar-sub-header"><a href="/blog/knowledge/js/es6/proxy.html#概述" class="sidebar-link">概述</a></li><li class="sidebar-sub-header"><a href="/blog/knowledge/js/es6/proxy.html#proxy-支持拦截的13种操作" class="sidebar-link">Proxy 支持拦截的13种操作</a></li><li class="sidebar-sub-header"><a href="/blog/knowledge/js/es6/proxy.html#特殊说明" class="sidebar-link">特殊说明</a></li></ul></li><li><a href="/blog/knowledge/js/es6/reflect.html" class="sidebar-link">Reflect 对象</a></li><li><a href="/blog/knowledge/js/es6/iterator.html" class="sidebar-link">Iterator(遍历器)</a></li><li><a href="/blog/knowledge/js/es6/map.html" class="sidebar-link">Map 对象</a></li></ul></section></li><li><section class="sidebar-group collapsable is-sub-group depth-1"><a href="/blog/knowledge/js/vue/" class="sidebar-heading clickable"><span>VUE</span> <span class="arrow right"></span></a> <!----></section></li><li><section class="sidebar-group collapsable is-sub-group depth-1"><a href="/blog/knowledge/js/other/" class="sidebar-heading clickable"><span>其他</span> <span class="arrow right"></span></a> <!----></section></li></ul></section></li></ul> </aside> <main class="page"> <div class="theme-default-content content__default"><h1 id="proxy-对象"><a href="#proxy-对象" class="header-anchor">#</a> Proxy 对象</h1> <h2 id="概述"><a href="#概述" class="header-anchor">#</a> 概述</h2> <ul><li>Proxy也就是代理，在目标对象前架设一层“拦截”，外界对该对象访问时，必须先通过这些拦截。</li> <li><code>ES6</code>原生提供<code>Proxy</code>构造函数，用来生产<code>Proxy</code>实例。</li></ul> <div class="language-javascript extra-class"><pre class="language-javascript"><code><span class="token keyword">var</span> proxy <span class="token operator">=</span> <span class="token keyword">new</span> <span class="token class-name">Proxy</span><span class="token punctuation">(</span>target<span class="token punctuation">,</span> handler<span class="token punctuation">)</span>
</code></pre></div><ul><li><code>target</code>代表要拦截的目标对象，<code>handler</code>也是一个对象，用于定制拦截的行为。</li></ul> <h2 id="proxy-支持拦截的13种操作"><a href="#proxy-支持拦截的13种操作" class="header-anchor">#</a> Proxy 支持拦截的13种操作</h2> <ul><li><code>get(target, propKey, receiver)</code>：拦截对象属性的读取，比如<code>proxy.foo</code>和<code>proxy['foo']</code>。</li> <li><code>set(target, propKey, value, receiver)</code>：拦截对象属性的设置，比如<code>proxy.foo = v</code>和<code>proxy['foo'] = v</code>。</li> <li><code>has(target, propKey)</code>：拦截<code>propKey in proxy</code>操作，返回一个布尔值。</li> <li><code>deleteProperty(target, propKey)</code>：拦截<code>delete proxy[propKey]</code>, 返回一个布尔值</li> <li><code>apply(target, ctx, args)</code>：拦截<code>Proxy</code>实例作为函数调用的操作，如：<code>proxy(...args)</code>、<code>proxy.call(ctx, ...args)</code>、<code>proxy.apply(...)</code>.</li> <li><code>ownkeys(target)</code>：</li> <li><code>getOwnPropertyDescriptor(target, propKey)</code>：</li> <li><code>defineProperty(target, propKey, propDesc)</code>：</li> <li><code>preventExtensions(target)</code>：</li> <li><code>getPrototypeOf(target)</code>：</li> <li><code>isExtensible(target)</code>：</li> <li><code>setPrototypeOf(target, proto)</code>：</li> <li><code>construct(target, args)</code>：</li></ul> <h2 id="特殊说明"><a href="#特殊说明" class="header-anchor">#</a> 特殊说明</h2> <ul><li><code>get(target, propKey, receiver)</code> <ol><li><code>target</code>为目标对象；<code>propKey</code>操作的属性名称；<code>receiver</code>为<code>proxy</code>实例本身(严格地说，是操作行为所针对的对象)（可选）</li> <li>若属性设置为不可配置(configurable),且不可写(writable),则<code>Proxy</code>不能去修改该属性的值，否则通过<code>Proxy</code>对象访问属性会报错。</li></ol></li></ul> <div class="language-javascript extra-class"><pre class="language-javascript"><code><span class="token keyword">const</span> proxy <span class="token operator">=</span> <span class="token keyword">new</span> <span class="token class-name">Proxy</span><span class="token punctuation">(</span><span class="token punctuation">{</span><span class="token punctuation">}</span><span class="token punctuation">,</span> <span class="token punctuation">{</span>
  <span class="token function-variable function">get</span><span class="token operator">:</span> <span class="token keyword">function</span><span class="token punctuation">(</span><span class="token parameter">target<span class="token punctuation">,</span> key<span class="token punctuation">,</span> receiver</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
    <span class="token keyword">return</span> receiver<span class="token punctuation">;</span>
  <span class="token punctuation">}</span>
<span class="token punctuation">}</span><span class="token punctuation">)</span><span class="token punctuation">;</span>

<span class="token comment">// proxy 对象的 a 属性是有 proxy 对象提供的，所以 receiver 指向 proxy 对象</span>
proxy<span class="token punctuation">.</span>a <span class="token operator">===</span> proxy <span class="token comment">// true</span>

<span class="token comment">// d 对象没有属性 a, 所以读取 a 时会去 d 的原型 proxy 对象找，</span>
<span class="token comment">// 此时 receiver 指向 d 对象,代表原始的读操作所在的那个对象。</span>
<span class="token keyword">const</span> d <span class="token operator">=</span> Object<span class="token punctuation">.</span><span class="token function">create</span><span class="token punctuation">(</span>proxy<span class="token punctuation">)</span><span class="token punctuation">;</span>
d<span class="token punctuation">.</span>a <span class="token operator">===</span> d <span class="token comment">// true</span>
</code></pre></div><div class="language-javascript extra-class"><pre class="language-javascript"><code><span class="token keyword">var</span> target <span class="token operator">=</span> Object<span class="token punctuation">.</span><span class="token function">defineProperty</span><span class="token punctuation">(</span> <span class="token punctuation">{</span><span class="token punctuation">}</span><span class="token punctuation">,</span> <span class="token string">'foo'</span><span class="token punctuation">,</span>
  <span class="token punctuation">{</span>
    value<span class="token operator">:</span> <span class="token number">123</span><span class="token punctuation">,</span>
    writable<span class="token operator">:</span> <span class="token boolean">false</span><span class="token punctuation">,</span>
    configurable<span class="token operator">:</span> <span class="token boolean">false</span>
  <span class="token punctuation">}</span>
 <span class="token punctuation">)</span><span class="token punctuation">;</span>

<span class="token keyword">var</span> handler <span class="token operator">=</span> <span class="token punctuation">{</span>
  <span class="token function">get</span><span class="token punctuation">(</span>target<span class="token punctuation">,</span> propKey<span class="token punctuation">)</span> <span class="token punctuation">{</span>
    <span class="token comment">// 1. 此时把原来的值123 修改成了 'abc', 所以会报错</span>
    <span class="token keyword">return</span> <span class="token string">'abc'</span><span class="token punctuation">;</span>
    <span class="token comment">// 2. 而这个值一样，相当于没有修改，所以不会报错</span>
    <span class="token comment">// return 123;</span>
    <span class="token comment">// 3. Reflect.get确保完成了原有的行为，值没变，所以不会报错</span>
    <span class="token comment">// return Reflect.get(target, propKey)</span>
  <span class="token punctuation">}</span>
<span class="token punctuation">}</span><span class="token punctuation">;</span>
<span class="token keyword">var</span> proxy <span class="token operator">=</span> <span class="token keyword">new</span> <span class="token class-name">Proxy</span><span class="token punctuation">(</span>target<span class="token punctuation">,</span> handler<span class="token punctuation">)</span><span class="token punctuation">;</span>
target<span class="token punctuation">.</span>foo
</code></pre></div><ul><li><code>set(target, propKey, value, receiver)</code> <ul><li><code>receiver</code>代表 <code>Proxy</code>实例本身（原始的操作行为所在的那个对象）</li> <li>严格模式下， <code>set</code>代理必须返回<code>true</code>（有值就行），否则就会报错。</li></ul></li></ul> <div class="language-javascript extra-class"><pre class="language-javascript"><code><span class="token keyword">const</span> handler <span class="token operator">=</span> <span class="token punctuation">{</span>
  <span class="token function-variable function">set</span><span class="token operator">:</span> <span class="token keyword">function</span><span class="token punctuation">(</span><span class="token parameter">obj<span class="token punctuation">,</span> prop<span class="token punctuation">,</span> value<span class="token punctuation">,</span> receiver</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
    obj<span class="token punctuation">[</span>prop<span class="token punctuation">]</span> <span class="token operator">=</span> receiver<span class="token punctuation">;</span>
  <span class="token punctuation">}</span>
<span class="token punctuation">}</span><span class="token punctuation">;</span>
<span class="token keyword">const</span> proxy <span class="token operator">=</span> <span class="token keyword">new</span> <span class="token class-name">Proxy</span><span class="token punctuation">(</span><span class="token punctuation">{</span><span class="token punctuation">}</span><span class="token punctuation">,</span> handler<span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token keyword">const</span> myObj <span class="token operator">=</span> <span class="token punctuation">{</span><span class="token punctuation">}</span><span class="token punctuation">;</span>
<span class="token comment">// 设置 myObj 的原型为 proxy</span>
Object<span class="token punctuation">.</span><span class="token function">setPrototypeOf</span><span class="token punctuation">(</span>myObj<span class="token punctuation">,</span> proxy<span class="token punctuation">)</span><span class="token punctuation">;</span>

<span class="token comment">// 此时 myObj 对象上没有属性 foo, 所以会去原型对象上 proxy 找，此时触发 set 方法，</span>
myObj<span class="token punctuation">.</span>foo <span class="token operator">=</span> <span class="token string">'bar'</span><span class="token punctuation">;</span>
<span class="token comment">// 此时 receiver 指向原始赋值行为所在的对象 myObj。</span>
myObj<span class="token punctuation">.</span>foo <span class="token operator">===</span> myObj <span class="token comment">// true</span>

<span class="token comment">// 若上方 改为</span>
<span class="token comment">// const myObj = { foo: 1 }</span>
<span class="token comment">// 则因为 myObj 有属性 foo, 所有不会触发 set 方法, 所以</span>
<span class="token comment">// myObj.foo === myObj // false</span>
</code></pre></div><ul><li><code>has(target, propKey)</code>，返回一个布尔值
<ul><li>拦截<code>propKey in target</code>, 但是不会拦截<code>for...in</code>操作。</li> <li>拦截的是<code>HasProperty</code>操作，而不是<code>HasOwnProperty</code>操作，即不去判断是否是对象自身的属性，还是继承的属性。</li> <li>目标对象的某个属性若不可配置<code>configurable</code>或者目标对象不可扩展<code>Object.preventExtensions(target)</code>, 则此时拦截对应的属性会报错。（不可配置，不可扩展还需详细了解）</li></ul></li> <li><code>deleteProperty(target, propKey)</code>，返回一个布尔值
<ul><li>在具体执行删除前抛出错误或者返回<code>false</code>,则删除不成功。</li> <li>目标对象的某个属性若不可配置<code>configurable</code>, 则此时拦截对应的属性会报错。</li></ul></li> <li><code>apply(target, ctx, args)</code>，target此时是一个函数</li></ul></div> <footer class="page-edit"><!----> <div class="last-updated"><span class="prefix">最后一次修改时间:</span> <span class="time">9/28/2020, 11:37:23 AM</span></div></footer> <div class="page-nav"><p class="inner"><span class="prev">
      ←
      <a href="/blog/knowledge/js/es6/generator.html" class="prev">
        Generator 函数
      </a></span> <span class="next"><a href="/blog/knowledge/js/es6/reflect.html">
        Reflect 对象
      </a>
      →
    </span></p></div> </main></div><div class="global-ui"></div></div>
    <script src="/blog/assets/js/app.2a047d56.js" defer></script><script src="/blog/assets/js/2.cc145974.js" defer></script><script src="/blog/assets/js/20.713720d3.js" defer></script>
  </body>
</html>
